package lowijs.XfDroid;

import java.io.*;

import lowijs.XfireClient.*;
import lowijs.XfireClient.event.*;
import lowijs.XfireClient.util.Util;

import android.app.*;
import android.content.*;
import android.os.*;
import android.preference.*;

public class XfDroidService extends Service implements XfireObserver {
	private static final int NM_NONE = 0;
	private static final int NM_ALL = 1;
	private static final int NM_OTHER = 2;
	
	private static XfireClient xfc = null;
	private static int notificationMode = NM_ALL;
	private static Friend activeFriend = null;
	private SharedPreferences prefs = null;
	private NotificationManager nm = null;
	
	private final FriendManager fm = FriendManager.getInstance();
		
	public void onCreate() {
		super.onCreate();
		EventManager.addObserver(this);
		xfc = new XfireClient();
		
		// Setup storage
		if(!Environment.getExternalStorageState()
				.equals(Environment.MEDIA_MOUNTED)) {
			Util.STORAGE_PATH = null;
		} else {
			Util.STORAGE_PATH = Environment.getExternalStorageDirectory()
					.getAbsolutePath() + "/xfdroid";
			File dir = new File(Util.STORAGE_PATH);
			dir.mkdirs();
		}
		
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
		nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
	}
	
	public void onStart(Intent i, int id) {
		super.onStart(i, id);
		String username = i.getStringExtra("username");
		String password = i.getStringExtra("password");
		
		xfc.connect(username, password);
	}
		
	public void onDestroy() {
		super.onDestroy();
		EventManager.removeObserver(this);
		if (xfc.isAlive())
			xfc.disconnect();
		
		activeFriend = null;
	}

	/*
	 * Package only
	 */
	static XfireClient getXfireClient() {
		return xfc;
	}
	
	public static void sendAllNotifications() {
		notificationMode = NM_ALL;
		activeFriend = null;
	}
	
	public static void sendNoNotifications() {
		notificationMode = NM_NONE;
		activeFriend = null;
	}
	
	public static void sendNoNotificationsFor(Friend f) {
		notificationMode = NM_OTHER;
		activeFriend = f;
	}

	public void handleEvent(XfireEvent event) {
		Friend f;
		
		switch(event.getEventType()) {
		case XfireEvent.XF_RECVIM:
			ReceiveImEvent e = (ReceiveImEvent)event;
			if (notificationMode == NM_NONE ||
					activeFriend == e.getFriend())
				return;
			
			f = e.getFriend();
			Bundle b = new Bundle();
			b.putByteArray("friend", f.getUserid());
			
			String msgFrom = getString(R.string.message_from);
			postNotification(msgFrom + " " + f.getNick(), f.getNick(),
					e.getIm().getMessage(), b, f.getUseridAsInt());
			return;
		case XfireEvent.XF_SENDIM:
			f = fm.getFriendBySid(((SendImEvent)event).getSid());
			nm.cancel(f.getUseridAsInt());
			return;
		case XfireEvent.XF_OFFLINE:
			stopSelf();
			return;
		}
	}
	
	private void postNotification(String ticker, String title, String message,
			Bundle extras, int id) {
		if (!prefs.getBoolean("XfDroid.sendNotifications", true))
			return;
		
		Notification n = new Notification(R.drawable.xfire_notif, ticker,
				System.currentTimeMillis());
		
		n.flags |= Notification.FLAG_AUTO_CANCEL;
		n.defaults |= Notification.DEFAULT_ALL;
		
		Intent i = new Intent(this, ConvoWindow.class);
		i.putExtras(extras);
		i.setFlags(Intent.FLAG_FROM_BACKGROUND
				| Intent.FLAG_ACTIVITY_SINGLE_TOP);
		
		PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
		
		n.setLatestEventInfo(this, title, message, pi);
		nm.notify(id, n);
	}

	/*
	 * Unused.
	 */
	public IBinder onBind(Intent arg0) {
		return null;
	}
}
